﻿using System;
using System.Collections.Generic;
using FluentNHibernate;
using NHibernate;
using NHibernate.Cfg;

namespace UserManagement.Dal.NH
{
    public class SessionFactory : ISessionFactory
    {
        #region private fields
        
        private readonly NHibernate.ISessionFactory _factory;
        private readonly ISessionSource _source;
        private IUnitOfWork _unitOfWork;

        #endregion private fields

        #region constructor
        
       public SessionFactory(PersistenceModel model) : this(null, model)
        {
        }

       public SessionFactory(IDictionary<string, string> properties, PersistenceModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var configuration = new Configuration();
            if (properties == null)
            {
                configuration.Configure();
            }
            else
            {
                configuration.AddProperties(properties);
            }

            model.Configure(configuration);
            _factory = configuration.BuildSessionFactory();
            //_source = new Mappings.SessionSource(_factory, model, configuration);
        }

        #endregion constructor

        #region public properties
        
        public IUnitOfWork CurrentUnitOfWork
        {
            get { return _unitOfWork ?? (_unitOfWork = GetUnitOfWork()); }
        }

        #endregion public properties

        #region public methods
        

        #endregion public methods

        #region private methods

        /// <summary>
        /// Gets the unit of work for current session.
        /// </summary>
        /// <returns></returns>
        private IUnitOfWork GetUnitOfWork()
        {
            ISession session = _factory.OpenSession();
            return new UnitOfWork(session);
        }

        #endregion private methods
    }
}